﻿using MediatR;
using S.Parturition.Domain;
using S.Parturition.Domain.Model;
using S.Parturition.Read.API.Application.Command;
using S.Parturition.Read.API.Dto;

namespace S.Parturition.Read.API.Application.CommandHandlers
{
    public class GetLambListHandler : IRequestHandler<GetLambListCommand, List<BreedLamdDto>>
    {

        private readonly MyDbContext dbContext;

        public GetLambListHandler(MyDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public async Task<List<BreedLamdDto>> Handle(GetLambListCommand request, CancellationToken cancellationToken)
        {
            List<ParturitionModel> parturitions = dbContext.ParturitionModel.Where(x => x.SheepStatus == false).ToList();
            List<LambRegistrationModel> lambs = dbContext.LambRegistrationModel.Where(x => x.SheepStatus == false).ToList();

            var list = (from p in parturitions
                        join l in lambs on p.EarTag equals l.MotherEar
                        select new BreedLamdDto()
                        {
                            ParturitionId = p.ParturitionId,
                            DeliveryDate = p.DeliveryDate,
                            LitterWeight = p.LitterWeight,
                            ShiftToBuild = p.ShiftToBuild,
                            ShiftToHuts = p.ShiftToHuts,

                            LambRegistrationId = l.LambRegistrationId,
                            BirthDate = l.BirthDate,
                            FatherEar = l.FatherEar,
                            MotherEar = l.MotherEar,
                            Sex = l.Sex,
                            EarTag = l.EarTag,
                            BirthWeight = l.BirthWeight,

                        }).Distinct().OrderByDescending(x => x.DeliveryDate).ToList();

            return list;
        }
    }
}
